import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  getStoreInfoList, getStoreInfo, deleteStoreInfo, saveStoreInfo,
} from '@/services/rentCenter/inverstment';
import {
  getBusinessById,
} from '@/services/rentCenter/basicSet';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const showImg = u => {
  window.open(u)
}
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '门店名称',
    key: 'name',
    align: 'center',
  },
  {
    title: '门店编号',
    key: 'storeNumber',
    align: 'center',
  },
  {
    title: '所属商户',
    key: 'merchantsName',
    align: 'center',
  },
  {
    title: '联系人',
    key: 'contactPerson',
    align: 'center',
  },
  {
    title: '手机号',
    key: 'phone',
    align: 'center',
  },
  {
    title: '业态',
    key: 'businessFullname',
    align: 'center',
  },
  {
    title: '品牌',
    key: 'brandName',
    align: 'center',
  },
  {
    title: '招商员',
    key: 'staffName',
    align: 'center',
  },
  {
    title: '签约状态',
    key: 'signStatus',
    render: params => (
      <span>{params.signStatus === 1 ? '已签约' : '未签约'}</span>
    ),
  },
];

const operatingStore = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [shoppers, setshoppers] = useState([]);
  const [firstId, setfirstId] = useState(undefined);
  const [shops, setshops] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    status: '1',
  });
  const [showtype2, setshowtype2] = useState(false);
  const [types, settypes] = useState([]);
  const [types2, settype2s] = useState([]);
  const [brands, setbrands] = useState([]);
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await getStoreInfoList(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
    if (r.data && r.data.length) {
      settypes(r.data)
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  // const removeRole = async record => {
  //   deleteShopCat({
  //     id: record.id,
  //   }).then(res => {
  //     if (res.data.code === '0') {
  //       const index = data.findIndex(e => e.id === record.id);
  //       setColData(() => {
  //         data.splice(index, 1);
  //         return [...data];
  //       });
  //     }
  //   })
  // };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const getType2 = () => {
    getBusinessById({ id: listQuery.businessId }).then(r => {
      if (r.data && r.data.code === '0') {
        settype2s(r.data.data)
      }
    })
  }
  const typeChange = v => {
    setfirstId(v)
    if (v) {
      if (!types2) {
        setshowtype2(true)
      }
      getType2()
    } else {
      settype2s([])
      setshowtype2(false)
    }
  }
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="模糊条件">
          <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} value={listQuery.condition} placeholder="门店名称，编号，联系人，联系电话，关联商户，招商员" />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="品牌">
          <Select onChange={v => { setListQuery({ ...listQuery, brandId: v }) }} placeholder="请选择品牌" value={listQuery.brandId}>
            { brands.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="签约状态">
          <Select onChange={v => { setListQuery({ ...listQuery, signStatus: v }) }} placeholder="请选择签约状态" value={listQuery.signStatus}>
            <Option key={0} value={0}>未签约</Option>
            <Option key={1} value={1}>已签约</Option>
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="一级业态">
          <Select onChange={typeChange} placeholder="请选择一级业态" value={firstId}>
            { types.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="二级业态">
          <Select onChange={v => { setListQuery({ ...listQuery, businessId: v }) }} placeholder="请选择二级业态" value={listQuery.businessId}>
            { types2.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = values
        params.status ? params.status = '1' : params.status = '0'
        console.log('Received values of form: ', values);
        saveStoreInfo({ storeBusiness: params }).then(() => {
          getList(listQuery)
          setState(!isShow);
        })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
    })
    setfirstId(undefined)
    setshowtype2(false)
    getList({
      pageNo: 1,
      pageSize: 10,
    })
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      default:
        return ''
    }
  };
  const catchange = v => {
    console.log(v)
  }
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="选择商户">
            {getFieldDecorator('merchantsId', {
              initialValue: info.merchantsId || '',
            })(<><Select placeholder="请选择商户">{shops.map(v => (<Option key={v.id}>{v.name}</Option>))}</Select></>)}
          </Form.Item>
          <Form.Item label="门店名称">
            {getFieldDecorator('name', {
              initialValue: info.name || '',
              rules: [
                {
                  required: true,
                  message: '请输入门店名称',
                },
              ],
            })(<Input placeholder="请输入门店名称" />)}
          </Form.Item>
          <Form.Item label="门店编号">
            {getFieldDecorator('storeNumber', {
              initialValue: info.storeNumber || '',
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item label="分店编号">
            {getFieldDecorator('branchStoreNumber', {
              initialValue: info.branchStoreNumber || '',
              rules: [
                {
                  required: true,
                  message: '请输入分店编号',
                },
              ],
            })(<Input placeholder="请输入分店编号" />)}
          </Form.Item>
          <Form.Item label="业态">
            <Select placeholder="请选择一级业态" onChange={catchange}>{types.map(v => (<Option key={v.id}>{v.businessName}</Option>))}</Select>
            {getFieldDecorator('businessId', {
              initialValue: info.businessId || '',
              rules: [
                {
                  required: true,
                  message: '请选择业态',
                },
              ],
            })(<><Select placeholder="请选择二级业态">{types2.map(v => (<Option key={v.id}>{v.businessName}</Option>))}</Select></>)}
          </Form.Item>
          <Form.Item label="品牌">
            {getFieldDecorator('brandId', {
              initialValue: info.brandId || '',
              rules: [
                {
                  required: true,
                  message: '请选择品牌',
                },
              ],
            })(<><Select placeholder="请选择品牌">{brands.map(v => (<Option key={v.id}>{v.name}</Option>))}</Select></>)}
          </Form.Item>
          <Form.Item label="联系人">
            {getFieldDecorator('contactPerson', {
              initialValue: info.contactPerson || '',
              rules: [
                {
                  required: true,
                  message: '请输入联系人',
                },
              ],
            })(<Input placeholder="请输入联系人" />)}
          </Form.Item>
          <Form.Item label="联系方式">
            {getFieldDecorator('phone', {
              initialValue: info.phone || '',
              rules: [
                {
                  required: true,
                  message: '请输入联系人手机号码',
                },
              ],
            })(<Input placeholder="请输入联系方式" />)}
          </Form.Item>
          <Form.Item label="身份证号码">
            {getFieldDecorator('contactPersonIdNo', {
              initialValue: info.contactPersonIdNo || '',
              rules: [
                {
                  required: true,
                  message: '请输入身份证号码',
                },
              ],
            })(<Input placeholder="请输入身份证号码" />)}
          </Form.Item>
          <Form.Item label="招商员">
            {getFieldDecorator('staffId', {
              initialValue: info.staffId || '',
              rules: [
                {
                  required: true,
                  message: '请选择招商员',
                },
              ],
            })(<><Select placeholder="请选择招商员">{shoppers.map(v => (<Option key={v.id}>{v.name}</Option>))}</Select></>)}
          </Form.Item>
          <Form.Item label="通讯地址">
            {getFieldDecorator('address', {
              initialValue: info.address || '',
              rules: [
                {
                  required: true,
                  message: '请输入通讯地址',
                },
              ],
            })(<Input placeholder="请输入通讯地址" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(operatingStore));
